package com.esg.esgproject.mp.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;


import java.io.File;
import java.util.HashMap;
import java.util.Optional;

/**
 * @author Z100
 * @create 2021-08-12 16:09
 * @desc
 **/
@RestController
@RequiredArgsConstructor
@Api(tags = "图片上传管理")
@RequestMapping("/api/file")
public class UploadImgController {

//    @Value("${file.imgPath}")
    private static  String filePath= "C:\\esg\\file\\";
    //

//    @Value("${file.imgURL}")
    private static String url="localhost:7777/api/file/";
    //="localhost:7777/api/file/"




    @ApiOperation("上传图片")
    @PostMapping("/upload")
    private ResponseEntity<Object> upload(@RequestParam("file") MultipartFile file) {
        if(file.isEmpty()){
            System.out.println("文件为空!");
        }
        String OriginalFilename = file.getOriginalFilename();
        String fileName = System.currentTimeMillis()+"."+OriginalFilename.substring(OriginalFilename.lastIndexOf(".")+1);

        File dest = new File(filePath+fileName);
        if(!dest.getParentFile().exists()){dest.getParentFile().mkdirs();}
        try {
            file.transferTo(dest);
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("上传失败");
        }
        HashMap<String, Object> ans = new HashMap<>();
        //todo filename有效性，有可能没存文件。filename就是 44649. 没有后缀

        String location=url+fileName;
        ans.put("url",location);
        return new ResponseEntity<>(ans, HttpStatus.OK);
    }
}
